package cn.imu.listener;

import cn.imu.entity.User;
import cn.imu.entity.UserCount;
import cn.imu.util.SessionUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.net.http.HttpRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/*
通过获取session中对于的IP，使用listener统计在线人数,存放在ServletContext中
 */
@WebListener
public class OnLinePersonListener implements ServletRequestListener,ServletContextListener, HttpSessionListener,HttpSessionAttributeListener {
    //用List来存储sessionid,ip以及fistTime
    private static List<UserCount> userCountList=new ArrayList<>();
    HttpServletRequest request;
    //number进行数量统计
    private int number;
    public OnLinePersonListener() {

    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        request=(HttpServletRequest) sre.getServletRequest();//获取request
        //
        Cookie[] cookies=request.getCookies();
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        /* This method is called when the servlet context is initialized(when the Web application is deployed). */
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        /* This method is called when the servlet Context is undeployed or Application Server shuts down. */
    }
    /**

     * 当有人访问时，就会有一个session被创建，监听到session创建，number就+1

     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */


    }


/*    //获取在线人数
   public static int getOline(){
       return userCountList.size();
   }*/

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
        number--;
        se.getSession().getServletContext().setAttribute("number",number);
        //list是存储在域对象ServletContext中，用于记录用户的的日志信息
        List<UserCount> list=(ArrayList<UserCount>) se.getSession().getServletContext().getAttribute("userList");
        //根据sessionid删除将要退出的用户信息
        SessionUtil.removeBySessionId(list,se.getSession().getId());
        se.getSession().getServletContext().setAttribute("userList",list);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        System.out.println("添加user到session中："+this);
        //如果在servlectcontext域对象中没有 userCountList，则创建
        userCountList=(List<UserCount>)se.getSession().getServletContext().getAttribute("userList");
        if(userCountList==null){
            userCountList=new ArrayList<>();
        }
        number++;

        //当session 创建的时候，监听统计在线人数 并且获取当前session的ip
        HttpSession session=se.getSession();
        User user=(User)se.getSession().getAttribute("user");
        System.out.println(user);
        String fisrtTimeString=new SimpleDateFormat("yyyy-MM--dd HH:mm:ss").format(new Date());
        String ip=request.getRemoteAddr();//获取客户端ip
        String sid=session.getId();//获取sessionId
        if(SessionUtil.getUserConutBySessionId(userCountList,sid)==null){//通过sessionId，查找用户
            //该用户不存在,新增用户
            UserCount userCount=new UserCount();
            if(SessionUtil.IsExist(userCountList,ip,user)){//判断ip和用户是否已经存在
                //该ip和user均不存在，则新增ip和user
                userCount.setSessionIdString(sid);
                userCount.setUser(user);
                userCount.setIpString(ip);
                userCount.setFistTimeString(fisrtTimeString);
                userCountList.add(userCount);
                session.getServletContext().setAttribute("userList",userCountList);
                //在线用户的数量存储到域对象ServletContext的number中
                session.getServletContext().setAttribute("number",number);
            }
        }

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        System.out.println("从session中移除user："+this);

    }
}
